<template>
  <div class="userLoginView">
    <h2 style="margin-bottom: 16px">用户登录</h2>
    <a-form
      :model="form"
      @submit="handleSubmit"
      label-align="left"
      auto-label-width
      style="max-width: 480px; margin: 0 auto"
    >
      <a-form-item
        :rules="[{ required: true, message: 'id不能为空' }]"
        field="id"
        label="学号 :"
      >
        <a-input v-model.number="form.id" placeholder="请输入学号" />
      </a-form-item>
      <a-form-item
        :rules="[
          { required: true, message: '密码不能为空' },
          { minLength: 4, message: '密码长度不能低于四位' },
        ]"
        field="password"
        tooltip="密码不少于4位"
        label="密码 :"
      >
        <a-input-password v-model="form.password" placeholder="请输入密码" />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" html-type="submit" style="margin: 0 auto">
          登录
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
import { reactive } from "vue";
import { UserControllerService, UserLoginRequest } from "../../../api";
import { Message } from "@arco-design/web-vue";
import store from "@/store";
import { useRouter } from "vue-router";

const router = useRouter();

const form = reactive<UserLoginRequest>({
  id: "",
  password: "",
});
const handleSubmit = async () => {
  if (!form.id || form.password.length < 4) {
    return;
  }
  const res = await UserControllerService.userLogin(form);
  if (res.code === 0) {
    Message.success(
      `登录成功！欢迎${
        res.data?.username ? `【${res.data.username}】` : ""
      }来到Linux OJ系统`
    );
    await store.dispatch("getLoginUser");
    await router.push({
      path: "/",
      replace: true,
    });
  } else {
    Message.error("用户名或密码错误");
  }
};
</script>
